import axios from 'axios'
import {useGetTokenStore} from '@/stores/index'
import {getToken, setToken, removeToken} from "@/utils/auth";
//创建axios
const service = axios.create({
    baseURL: import.meta.env.VITE_BAST_URL,
    timeout: 5000
})
service.interceptors.request.use(
    config => {
        const userToken = useGetTokenStore()
        if (userToken.token) {
            config.headers['X-token'] = getToken()
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    response =>{
        const userToken = useGetTokenStore()
        const res = response.data
        if(res.code === 1200){
            userToken.resetToken().then(()=>{
                location.reload()
            })
        }else if (res.code === 1100){
            return Promise.reject(new Error(res.message) || 'Error')
        }else{
            return res
        }
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)
export default service
